import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { isLoggedIn } from '@/services/auth'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/qa',
    name: 'qa',
    // 路由级代码分割，生成单独的chunk
    component: () => import('../views/QAView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/cases',
    name: 'cases',
    component: () => import('../views/CasesView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/config',
    name: 'config',
    component: () => import('../views/ConfigView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue'),
    meta: { guest: true }
  },
  {
    path: '/profile',
    name: 'profile',
    component: () => import('../views/ProfileView.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 全局前置守卫，确保用户已登录
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 用户未登录，重定向到登录页
    if (!isLoggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 保存目标路由，登录后可以重定向回来
      });
    } else {
      next(); // 已登录，继续导航
    }
  } else if (to.matched.some(record => record.meta.guest)) {
    // 访客页面（如登录页），已登录用户应该重定向到首页
    if (isLoggedIn()) {
      next({ path: '/' });
    } else {
      next(); // 未登录，允许访问
    }
  } else {
    next(); // 不需要认证的页面，直接继续
  }
});

export default router